{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "\n",
    "def rotate_image(mat, angle):\n",
    "    \"\"\"\n",
    "    Rotates an image (angle in degrees) and expands image to avoid cropping\n",
    "    \"\"\"\n",
    "\n",
    "    height, width = mat.shape[:2] # image shape has 3 dimensions\n",
    "    image_center = (width/2, height/2) # getRotationMatrix2D needs coordinates in reverse order (width, height) compared to shape\n",
    "\n",
    "    rotation_mat = cv2.getRotationMatrix2D(image_center, angle, 1.)\n",
    "\n",
    "    # rotation calculates the cos and sin, taking absolutes of those.\n",
    "    abs_cos = abs(rotation_mat[0,0]) \n",
    "    abs_sin = abs(rotation_mat[0,1])\n",
    "\n",
    "    # find the new width and height bounds\n",
    "    bound_w = int(height * abs_sin + width * abs_cos)\n",
    "    bound_h = int(height * abs_cos + width * abs_sin)\n",
    "\n",
    "    # subtract old image center (bringing image back to origo) and adding the new image center coordinates\n",
    "    rotation_mat[0, 2] += bound_w/2 - image_center[0]\n",
    "    rotation_mat[1, 2] += bound_h/2 - image_center[1]\n",
    "\n",
    "    # rotate image with the new bounds and translated rotation matrix\n",
    "    rotated_mat = cv2.warpAffine(mat, rotation_mat, (bound_w, bound_h))\n",
    "    return rotated_mat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import cv2\n",
    "ll = os.listdir('test/')\n",
    "for i in ll:\n",
    "    \n",
    "\n",
    "    src = cv2.imread(\"test/\"+i, cv2.IMREAD_COLOR)\n",
    "\n",
    "    rr = rotate_image(src, -90)\n",
    "    cv2.imwrite(\"test/\"+i,rr)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
